import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
import { Form, Input, Tooltip, Row, Col, Checkbox, Button, message, } from 'antd';
import { QuestionCircleOutlined, InfoCircleOutlined } from '@ant-design/icons';

import { PostApi, GetApi } from '../../api/request'
import { Md5Psd, setSession, getSession, clearSession, setLocalStorage } from '../../utils/utils'

const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 6,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 18,
        },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 4,
        },
    },
};

class RegisterForm extends Component {
    state = {
        form: 0,
        getCodeTip: '获取',
        disabled: false,
        email: ''
    }
    onFinish = async values => {
        try {
            message.destroy();
            values.password = Md5Psd(values.password)
            values.confirm = Md5Psd(values.confirm)
            const key = 'updatable';
            message.loading({ content: '正在请求服务器...', key });
            let res = await PostApi('/register', values)
            if (res.data.code === 200) {
                setLocalStorage('token', res.data.token)
                setLocalStorage('userInfo', JSON.stringify(res.data.data))
                message.success({
                    content: res.data.msg, key, duration: 1, onClose: () => {
                        this.props.history.push('./disk')
                    }
                });
            } else if (res.data.code === 205) {
                message.warning({ content: res.data.msg, key, duration: 2 });
            } else {
                message.error({ content: res.data.msg, key, duration: 2 });
            }
        } catch (error) {
            message.destroy();
            if (error.indexOf("Network Error") !== -1) {
                message.error({ content: '后台服务器故障，请稍后重试！', duration: 2 });
            }

        }
    };
    componentDidMount() {
        if (getSession('num')) {
            let num = getSession('num')
            this.setState({
                getCodeTip: num + "s",
                disabled: true,
            })
            let timer = setInterval(() => {
                num--;
                if (num <= 0) {
                    clearInterval(timer);
                    clearSession('num')
                    this.setState({
                        getCodeTip: '获取',
                        disabled: false,
                        startNum: false
                    })
                } else {
                    this.setState({
                        getCodeTip: num + "s",
                        disabled: true,
                    })
                    setSession("num", num)
                }
            }, 1000)
        }
    }
    getCode = async () => {
        try {
            message.destroy();
            if (this.state.email === '') {
                message.warning({ content: '请输入邮箱账号！', duration: 5 });
            } else {
                let num = 60;
                setSession("num", num)
                this.setState({
                    getCodeTip: num + "s",
                    disabled: true
                })
                let timer = setInterval(() => {
                    num--;
                    if (num <= 0) {
                        clearInterval(timer);
                        clearSession('num')
                        this.setState({
                            getCodeTip: '获取',
                            disabled: false,
                            startNum: false
                        })
                    } else {
                        this.setState({
                            getCodeTip: num + "s",
                            disabled: true,
                        })
                        setSession("num", num)
                    }
                }, 1000)
                let email = { email: this.state.email }
                let res = await GetApi('/code', email)
                if (res.data.code === 200) {
                    message.success({ content: res.data.msg, duration: 2 });
                } else if (res.data.code === 205) {
                    message.warning({ content: res.data.msg, duration: 0 });
                    clearInterval(timer);
                    clearSession('num')
                    this.setState({
                        getCodeTip: '获取',
                        disabled: false,
                        email: ''
                    })
                } else {
                    message.error({ content: res.data.msg, duration: 5 });
                    clearInterval(timer);
                    clearSession('num')
                    this.setState({
                        getCodeTip: '获取',
                        disabled: false,
                        email: ''
                    })
                }

            }
        } catch (error) {
            if (error.indexOf("Network Error") !== -1) {
                message.error({ content: '后台服务器故障，请稍后重试！', duration: 0 });
            }
        }
    }
    inputChange = (e) => {
        let email = e.target.value
        let reg = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
        if (reg.test(email)) {
            this.setState({ email })
        }
    }
    render() {
        return (
            <Form
                {...formItemLayout} form={this.form} name="register"
                onFinish={this.onFinish} scrollToFirstError>
                <Form.Item
                    name="email"
                    label={
                        <span>
                            邮箱&nbsp;
                                     <Tooltip title="支持所有邮箱账户！">
                                <QuestionCircleOutlined />
                            </Tooltip>
                        </span>
                    }
                    rules={[
                        { type: 'email', message: '邮箱格式错误!', },
                        { required: true, message: '请输入邮箱账号', },]}>
                    <Input size="large" placeholder="邮箱账号" onChange={this.inputChange} allowClear suffix={
                        <Tooltip title="邮箱号可作为登录账号！">
                            <InfoCircleOutlined style={{ color: 'rgba(0,0,0,.45)' }} />
                        </Tooltip>
                    } />
                </Form.Item>
                <Form.Item
                    name="password"
                    label={
                        <span>密码&nbsp;<Tooltip title="字母+数字+特殊符号更安全"><QuestionCircleOutlined />
                        </Tooltip>
                        </span>
                    }
                    rules={[{ required: true, message: '请输入密码!' },]}
                    hasFeedback>
                    <Input.Password size="large" allowClear placeholder="设置密码" />
                </Form.Item>
                <Form.Item
                    name="confirm"
                    label="确认密码"
                    dependencies={['password']}
                    hasFeedback
                    rules={[{ required: true, message: '请再次输入密码!', },
                    ({ getFieldValue }) => ({
                        validator(rule, value) {
                            if (!value || getFieldValue('password') === value) {
                                return Promise.resolve();
                            }
                            return Promise.reject('二次密码不一致!');
                        },
                    }),
                    ]}>
                    <Input.Password size="large" allowClear placeholder="确认密码" />
                </Form.Item>

                <Form.Item label={
                    <span>
                        验证码
                    </span>
                }>
                    <Row gutter={8}>
                        <Col span={13}>
                            <Form.Item
                                name="captcha"
                                noStyle
                                rules={[{ required: true, message: '请输入邮箱验证码!', },
                                ]}>
                                <Input size="large" allowClear placeholder="验证码" />
                            </Form.Item>
                        </Col>
                        <Col span={10}>
                            <Button size="large" onClick={this.getCode} disabled={this.state.disabled}>{this.state.getCodeTip}</Button>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item
                    name="agreement"
                    valuePropName="checked"
                    style={{ textAlign: 'center' }}
                    rules={[{
                        validator: (_, value) =>
                            value ? Promise.resolve() : Promise.reject('你应该同意协议！'),
                    },
                    ]}
                    {...tailFormItemLayout}>
                    <Checkbox>我已阅读 <a href="/#">协议</a></Checkbox>
                </Form.Item>
                <Form.Item {...tailFormItemLayout}>
                    <Button size="large" type="primary" style={{ width: "100%" }} htmlType="submit">注册</Button>
                </Form.Item>

            </Form>
        );
    }
};
export default withRouter(RegisterForm)